/**
 * 
 */
package com.wsj.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author fengbin
 * @version 1.1  2008-7-24
 *
 */
public class ProductsBaseFilter implements Filter
{
	
	   protected FilterConfig filterConfig = null;
	   
	   //跳转的页面
	    protected String toPage = null;
	    
	    private Log logger =LogFactory.getLog(this.getClass());
	    

	public void destroy() 
	{
		 this.toPage  = null;
	     this.filterConfig = null;	
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException 
	{
		HttpServletRequest httpReq =(HttpServletRequest)request;
    	HttpServletResponse httpResp = (HttpServletResponse)response;
    	
    	//校验请求路径
    	if(checkPath(httpReq))
    	{ 		
    		ServletContext context = filterConfig.getServletContext();
    		
    		
    		logger.error("\n\n RequestURI:"+httpReq.getRequestURI());
//    		logger.error("\n\n QueryString:"+httpReq.getQueryString());
//    		logger.error("\n\n ServletPath:"+httpReq.getServletPath());
    		
//    		logger.error("\n\n ContextPath:"+context.getContextPath());
//    		 String strBackUrl = "http://" + httpReq.getServerName() + ":" + httpReq.getServerPort() + httpReq.getContextPath() + httpReq.getServletPath() + "?" + this.codeToString(httpReq.getQueryString());
//    		 
//    		 String  realPath  =  "http://"  +  httpReq.getServerName()  +  ":"  +  httpReq.getServerPort()  +  httpReq.getContextPath()+httpReq.getServletPath().substring(0,httpReq.getServletPath().lastIndexOf("/")+1);  
//
//    		   
//    		 logger.error("\n\n strBackUrl:"+strBackUrl);
//    		 
//    		 logger.error("\n\n realPath:"+realPath);
    		 
    		 
    		 
    		//解析出的查询路径"/html/productsBase/pb174.html"
    		 String queryPath=httpReq.getRequestURI();
    		 
    		 //解析出id
    		 String id=this.parseId(queryPath);
    		 
            RequestDispatcher rd =context.getRequestDispatcher(toPage+id);
            if (rd == null) 
            {
                httpResp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"Login page doesn't exist");
            }
            
//            请求转发
            rd.forward(request, response);
            return ;
    	}
        chain.doFilter(request, response);
		
	}

	
	/***
	 * 解析出请求路径中的id
	 * @param queryPath
	 * @return
	 */
	private String parseId(String queryPath) 
	{
		String id="";
		if(queryPath!=null && !queryPath.equals(""))
		{
			Integer size=queryPath.lastIndexOf("/");
			String withHtml=queryPath.substring(size+1, queryPath.length());
			
			//将pb1.html 解析 出1
			id=withHtml.substring(2,withHtml.length()-5);
		}
		
		return id;
	}

	/**
     * 格式化中文字符，防止出现乱码
     * @param str
     * @return
     */
    public  String codeToString(String str) 
    {
        String strString = str;
        try {
            byte tempB[] = strString.getBytes("ISO-8859-1");
            strString = new String(tempB);
            return strString;
        } catch (Exception e) {
            return strString;
        }
    } 

    
    
	
	/****
	 * 校验请求路径
	 * @param httpReq
	 * @return
	 */
	private boolean checkPath(HttpServletRequest httpReq) 
	{
		
		return true;
	}

	
	/***
	 * 初始化
	 */
	public void init(FilterConfig filterConfig) throws ServletException 
	{
		  this.filterConfig = filterConfig;
	        this.toPage  = filterConfig.getInitParameter("toPage");
	        if(toPage==null)
	        {
	                throw new ServletException("toPage init param missing");
	        }
		
	}
	
	

}
